//
//  GSNewsViewController.m
//  GameSky
//
//  Created by lanou on 16/1/10.
//  Copyright © 2016年 NiRongfei. All rights reserved.
//

#import "GSNewsViewController.h"
#import "GSNewsTableViewController.h"
#import "GSNewsMainCell.h"
#import "GSNewsImageCell.h"
#import "GSNewsAllChannel.h"
#import "GSAppUIOrderView.h"

@interface GSNewsViewController ()<UIScrollViewDelegate,GSAppUIOrderViewDelegate>

// 主scrollView
@property (nonatomic, strong) UIScrollView *mainScrollView;
@property (nonatomic, strong) UITableView *tableView;

// 所有的频道数组
@property (nonatomic, strong) NSMutableArray *allChannelArray;

// 标题存放数组
@property (nonatomic, strong) NSMutableArray *titleListArray;


@property (nonatomic, strong) GSAppUIOrderView *orderView;

// 加条件判断是否转动了右按钮箭头
@property (nonatomic, assign) BOOL isRightSelected;

@property (nonatomic, strong) NSMutableArray *allChannelTitle;

@property (nonatomic, strong) NSMutableDictionary *titleDic;


@end

@implementation GSNewsViewController

#pragma mark ----- 懒加载标题栏列表
- (NSMutableArray *)titleListArray
{
    if (_titleListArray == nil) {

        
        _titleListArray = [NSMutableArray arrayWithObjects:@"头条",@"游戏",@"趣味",@"福利",@"手游",@"影视",@"科技",@"动漫",@"点评",@"产业", nil];

    }
    
    return _titleListArray;
}

// 添加控制器
- (void)addController:(NSMutableArray *)titleArray
{
    for (int i = 0; i < 10; i++) {
        
        GSNewsTableViewController *newsTableVC = [[GSNewsTableViewController alloc]initWithStyle:(UITableViewStyleGrouped)];
        
        newsTableVC.title = titleArray[i];
        
        
        [self.titleDic setObject:newsTableVC forKey:titleArray[i]];
        
        [self addChildViewController:newsTableVC];
    }
}




/**
 *  添加label
 */
- (void)addLabel:(NSMutableArray *)titleArray
{
    for (int i = 0; i < 10; i++) {
        
        CGFloat lblW = 70;
        
        CGFloat lblH = 30;
        
        CGFloat lblY = 3;
        
        CGFloat lblX = i * lblW;
        
        GSTitleLabel *lbl1 = [[GSTitleLabel alloc]init];
        
        // 取出子控制器
//        UIViewController *vc = self.childViewControllers[i];
        
        // 通过控制器的标题给label赋值,控制器的标题是由数组赋值的
//        lbl1.text = vc.title;
        
        lbl1.text = titleArray[i];
        
        lbl1.frame = CGRectMake(lblX, lblY, lblW, lblH);
        
        lbl1.font = [UIFont fontWithName:@"HYQiHei" size:19];
        
        lbl1.textColor = [UIColor whiteColor];
        
        [self.navBar.titleScrollView addSubview:lbl1];
        
        lbl1.tag = i + 100;
        
        lbl1.userInteractionEnabled = YES;
        
        [lbl1 addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(lblClick:)]];
    }
    
    self.navBar.titleScrollView.contentSize = CGSizeMake(70 * 10, 0);
    
    
    
}

/** 标题栏label的点击事件 */
- (void)lblClick:(UITapGestureRecognizer *)recognizer
{
    GSTitleLabel *titleLabel = (GSTitleLabel *)recognizer.view;
    
    CGFloat offsetX =  (titleLabel.tag - 100) * kScreenWidth;

    [self.mainScrollView setContentOffset:CGPointMake(offsetX, 0) animated:YES];
}

// 数据源
- (NSMutableArray *)allChannelArray {
    if (!_allChannelArray) {
        _allChannelArray = [NSMutableArray array];
    }
    return _allChannelArray;
}

// 加载数据
- (void)addData
{

        NSMutableDictionary *paraDict = [NSMutableDictionary dictionary];
    
        paraDict[@"request"] = @{@"type":@0};
    
    self.allChannelTitle = [NSMutableArray array];
    
    [GSNetworkManager requestWithUrlStr:@"http://appapi2.gamersky.com/v2/allchannel" paraDict:paraDict method:POST success:^(NSURLResponse *response, NSData *data) {
        NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        NSArray *resultArray = dataDict[@"result"];
        for (NSDictionary *oneDic in resultArray) {
            GSNewsAllChannel *allChannel = [[GSNewsAllChannel alloc]init];
            
            [allChannel setValuesForKeysWithDictionary:oneDic];
            
            [self.allChannelArray addObject:allChannel];
            
            [self.allChannelTitle addObject:allChannel.nodeName];
        }
        
    } failure:^(NSError *error) {
        
    }];
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    
    
    self.titleDic = [NSMutableDictionary dictionary];

    [self.navBar.rightButton setImage:[UIImage imageNamed: @"common_Icon_ExtensionContentButton_20x20_UIMode_Day.png"] forState:(UIControlStateNormal)];
    
    /** 点击导航条左边的按钮 */
    [self.navBar.leftButton addTarget:self action:@selector(showMenu:) forControlEvents:(UIControlEventTouchUpInside)];
    
    
    /** 点击导航条右边的按钮 */
    [self.navBar.rightButton addTarget:self action:@selector(showOrderView:) forControlEvents:(UIControlEventTouchUpInside)];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    // 加载数据
    [self addData];
    
    // 添加10个子控制器
    [self addController:self.titleListArray];
    
    // 添加label
    [self addLabel:self.titleListArray];
    
    [self addSubviews];
    
    self.orderView = [[GSAppUIOrderView alloc]init];
    
    self.orderView.titleListArray = self.titleListArray;
    
    self.orderView.frame = CGRectMake(0, 64, kScreenWidth, kScreenHeight);
    
    self.orderView.alpha = 0;
    self.orderView.delegate = self;
    
    
    self.isRightSelected = YES;
    
}



/**
 *  右按钮点击显示排列视图
 */
- (void)showOrderView:(UIButton *)rightButton
{

    if (self.isRightSelected == YES) {
        
        [self.view addSubview: self.orderView];
        
        [UIView animateWithDuration:0.2 animations:^{
            
             self.orderView.alpha = 1;
            
            self.navBar.rightButton.transform = CGAffineTransformRotate(self.navBar.rightButton.transform, (M_PI));
            
        }];

        self.isRightSelected = NO;
        
        
    }else{
        
        [UIView animateWithDuration:0.2 animations:^{
            
            self.navBar.rightButton.transform = CGAffineTransformRotate(self.navBar.rightButton.transform, (M_PI));
            
             self.orderView.alpha = 0;
            
            [self.orderView removeFromSuperview];
            
            self.isRightSelected = YES;
            
        }];
    }

}

#pragma mark ---- GSAppUIOrderView 的代理
- (void)GSAppUIOrderViewTapClick:(GSAppUIOrderView *)order
{
    if (self.isRightSelected == NO) {
        
        [UIView animateWithDuration:0.2 animations:^{
            
            [order removeFromSuperview];
            
             self.navBar.rightButton.transform = CGAffineTransformRotate(self.navBar.rightButton.transform, (M_PI));
            
            self.isRightSelected = YES;
            
        }];
    }
    
    for (UILabel *label in self.navBar.titleScrollView.subviews) {
        
        [label removeFromSuperview];
        
    }
    
    [self addLabel:self.titleListArray];
    
    for (int i = 0; i < 10; i++) {
        
        GSNewsTableViewController *tab = [self.titleDic objectForKey:self.titleListArray[i]];
        
        [tab removeFromParentViewController];
        
    }
    
    [self addController:self.titleListArray];
    
}

- (void)GSAppUIOrderViewButtonTitle:(NSMutableArray *)buttonTitle
{

    for (int i = 0; i < 10; i++) {
        
        self.titleListArray[i] = buttonTitle[i];
        
    }

}


- (void)addSubviews {
    self.mainScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64, kScreenWidth, kScreenHeight - 64)];
    self.mainScrollView.contentSize = CGSizeMake(kScreenWidth * self.childViewControllers.count, kScreenHeight - 64);
    // 夜间模式
    self.mainScrollView.dk_backgroundColorPicker = DKColorWithRGB(0xffffff, 0x343434);
    
    self.mainScrollView.pagingEnabled = YES;
    self.mainScrollView.showsVerticalScrollIndicator = NO;
    
    self.mainScrollView.delegate = self;
    
    self.mainScrollView.bounces = NO;
    
    [self.view addSubview:self.mainScrollView];
    
    
    // 添加默认的控制器 (就是第一个控制器(头条))
    GSNewsTableViewController *vc = self.childViewControllers.firstObject;
    
    vc.view.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight - 44 - 64);

    vc.nodeId = @0;
    
    [self.mainScrollView addSubview:vc.view];
    
    // 让第一个label比例变大
    GSTitleLabel *label = self.navBar.titleScrollView.subviews.firstObject;
    
    label.scale = 1.0;

    
}

#pragma  mark --- 主scrollView滚动的代理
// 滚动结束时调用
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    // 获得索引
    NSInteger index = scrollView.contentOffset.x / self.mainScrollView.width;
    /**
     * 滚动标题栏
     */
    // 取得索引所对应的label
    GSTitleLabel *titleLabel = self.navBar.titleScrollView.subviews[index];
    
    
    
    // 当前的label的中心点 - 标题scrollView实际长度的一半(也就是在偏移量大于标题一半的时候,开始滚动)
    CGFloat offsetX = titleLabel.center.x - self.navBar.titleScrollView.width * 0.5;
    
    // 最大的偏移量是标题栏的scrollView的最大滚动尺寸 - scrollView的实际尺寸
    CGFloat offsetMax = self.navBar.titleScrollView.contentSize.width - self.navBar.titleScrollView.width;
    
    if (offsetX < 0) {
        
        offsetX = 0;
        
    }else if (offsetX > offsetMax){
        
        offsetX = offsetMax;
        
    }
    
    
    [self.navBar.titleScrollView setContentOffset:CGPointMake(offsetX, self.navBar.titleScrollView.contentOffset.y) animated:YES];

    
    // 滚动结束的时候,添加控制器
    GSNewsTableViewController *newsVC = self.childViewControllers[index];
    
    
    newsVC.index = index;
    
    if (index >=1) {
        
        NSUInteger indexOne = [self.allChannelTitle indexOfObject:titleLabel.text];
        
        
        GSNewsAllChannel *model = self.allChannelArray[indexOne];
        newsVC.nodeId = model.nodeId;
        
        [newsVC.tableView reloadData];
        
    }

    [self.navBar.titleScrollView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        if (idx != index) {
            
            GSTitleLabel *tempLabel = self.navBar.titleScrollView.subviews[idx];
            
            tempLabel.scale = 0.0;
            
        }

    }];
    
    if (newsVC.view.superview) {
        
        return;
        
    }

    
    newsVC.view.frame = CGRectMake(scrollView.bounds.origin.x, 0, kScreenWidth, kScreenHeight - 44 - 64);
    
    [self.mainScrollView addSubview:newsVC.view];


    
}

// 滚动结束(手势导致)
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self scrollViewDidEndScrollingAnimation:scrollView];
}

// 正在滚动
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    // 取得不断变化的偏移量
    CGFloat value = ABS(scrollView.contentOffset.x / scrollView.width);
    
    // 左边的索引 (用int类型,则永远为整数)
    NSUInteger leftIndex = (int)value;
    
    // 右边的索引 (等于左边的索引加上1)
    NSUInteger rightIndex = (int)leftIndex + 1;
    
    // 右边的字体比例是(value是不断变大的,从0.0 -- 1.0 再从1.0 -- 2.0 而这个时候,,正好用不断变化的值,减去变化值的整数(比如0.0 -- 1.0 都减去0))这样就能得到字体变大的比例
    CGFloat scaleRight = value- leftIndex;
    
    CGFloat scaleLeft = 1- scaleRight;
    
    GSTitleLabel *leftLabel = self.navBar.titleScrollView.subviews[leftIndex];
    
    leftLabel.scale = scaleLeft;
    
    // 如果右边的索引小于最后一个(考虑右边的索引)
    if (rightIndex < self.navBar.subviews.count) {
        
        GSTitleLabel *rightLabel = self.navBar.titleScrollView.subviews[rightIndex];
        
        rightLabel.scale = scaleRight;
        
    }

}

@end
